<?php
/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2018/12/30
 * Time: 23:59
 */

namespace app\common\model;


class BaiduOcr
{
    private  $appid ='9360309';
    private  $api_key ='f94FyaKX2LKx0GWBoddFVpxa';
    private  $secret_key ='oGhM9QqHH6qslErF1LH8etP6Ber5adDz';
    private $en_name ='baidu_ocr';
    private $base_url = 'https://aip.baidubce.com/rest/2.0/ocr/v1/';


   public function getAccess(){
       $tokenRet =$this->findAccessToken();

       if( $tokenRet['error']==0){
           return $tokenRet['data']['access_token'];
       }
       return false;
   }

    /*通用ocr识别
    $image图片base64，跟网址二选一
    $image_url 图片网址，跟片base64二选一
    $language_type  - CHN_ENG：中英文混合；
                    - ENG：英文；
                    - POR：葡萄牙语；
                    - FRE：法语；
                    - GER：德语；
                    - ITA：意大利语；
                    - SPA：西班牙语；
                    - RUS：俄语；
                    - JAP：日语；
                    - KOR：韩语
      $detect_direction 是否检测图像朝向，默认不检测，即：false。朝向是指输入图像是正常方向、逆时针旋转90/180/270度。
      $detect_language 是否检测语言，默认不检测。当前支持（中文、英语、日语、韩语）
      $probability 是否返回识别结果中每一行的置信度
     * */
    public function generalBasic($image='',$image_url='',$language_type='CHN_ENG',$detect_direction=false,$detect_language=false,$probability=false){
        $action = 'general_basic';
        $url = $this->base_url.$action;
        $form =array();
        if(empty($image)&&empty($image_url)){
            return array('error'=>1,'msg'=>'图片网址，跟片base64必须二选一');
        }
        if(empty($image)){
            $form['url'] = $image_url;
        }else{
            $form['image'] = $image;
        }
        $form['language_type'] = $language_type;
        $form['detect_direction'] = $detect_direction;
        $form['detect_language'] = $detect_language;
        $form['probability'] = $probability;

        $form['access_token']= $this->getAccess();
        if( $form['access_token']==false){
            return array('error'=>1,'msg'=>'access_token获取失败');
        }

        return array('error'=>0,'msg'=>'获取成功','data'=>json_decode($this->request_post($url,$form),true));
    }

    /*通用文字识别（高精度版）
     *$image_base64 图像数据，base64编码后进行urlencode，要求base64编码和urlencode后大小不超过4M，最短边至少15px，最长边最大4096px,支持jpg/png/bmp格式
     * detect_direction 是否检测图像朝向，默认不检测，即：false。朝向是指输入图像是正常方向、逆时针旋转90/180/270度
     * probability 是否返回识别结果中每一行的置信度
     * */
    public function accurateBasic($image_base64,$detect_direction=false,$probability=false){
        $action = 'accurate_basic';
        $url = $this->base_url.$action;
        $form =array();
        $form['image'] = $image_base64;
        $form['detect_direction'] = $detect_direction;
        $form['probability'] = $probability;
        $form['access_token']= $this->getAccess();
        if( $form['access_token']==false){
            return array('error'=>1,'msg'=>'access_token获取失败');
        }
        return array('error'=>0,'msg'=>'获取成功','data'=>json_decode($this->request_post($url,$form),true));
    }



    /*获取访问token
     * */
    public function findAccessToken(){
        $configModel = new Configs();
        $en_name = 'baidu_ocr';
        $tokenInfo = $configModel->findByEnName($en_name);

        //没有存档
        if(empty($tokenInfo)){
            $tokenInfo =$this->updateAccessToken();
            if($tokenInfo['error']==1){
                return array('error'=>1,'msg'=>$tokenInfo['msg']);
            }
            $tokenArr = $tokenInfo['data'];
            return array('error'=>1,'msg'=>'获取成功','data'=>$tokenArr);
        }

        //
         $tokenArr = json_decode($tokenInfo['config'],true);
         $expire_time  = $tokenInfo['updatetime']+$tokenArr['expires_in'];

            //到期3分钟之前刷新accessToken
         if($expire_time-300<time()){
                $tokenInfo =$this->updateAccessToken();
                if($tokenInfo['error']==1){
                    return array('error'=>1,'msg'=>$tokenInfo['msg']);
                }
                $tokenArr = $tokenInfo['data'];
         }else{
                $tokenArr = json_decode($tokenInfo['config'],true);
         }
        return array('error'=>0,'msg'=>'获取成功','data'=>$tokenArr);
    }

    /*获取access token
    *有效期30天
     * */
    public function updateAccessToken(){
        $url = 'https://aip.baidubce.com/oauth/2.0/token';
        $post_data['grant_type']       = 'client_credentials';
        $post_data['client_id']      = $this->api_key;
        $post_data['client_secret'] = $this->secret_key;
        $o = "";
        foreach ( $post_data as $k => $v )
        {
            $o.= "$k=" . urlencode( $v ). "&" ;
        }
        $post_data = substr($o,0,-1);
        $tokenJson =$this->request_post($url, $post_data);

        if(empty($tokenJson)){
            return array('error'=>1,'msg'=>'接口返回空数控');
        }
        $tokenArr = json_decode($tokenJson,true);
        if(!isset($tokenArr['access_token'])){
            return array('error'=>1,'msg'=>'接口返回空access_token');
        }

        $configModel = new Configs();
        $data['config'] = json_encode($tokenArr);
        if( $configModel->updateByEnName($data,$this->en_name)){
            return array('error'=>0,'msg'=>'access_token更新成功','data'=>$tokenArr);
        }
             return array('error'=>1,'msg'=>'access_token保存失败');
    }


    public  function request_post($url = '', $param = '') {
        if (empty($url) || empty($param)) {
            return false;
        }
        $postUrl = $url;
        $curlPost = $param;
        $curl = curl_init();//初始化curl
        curl_setopt($curl, CURLOPT_URL,$postUrl);//抓取指定网页
        curl_setopt($curl, CURLOPT_HEADER, 0);//设置header
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上
        curl_setopt($curl, CURLOPT_POST, 1);//post提交方式
        curl_setopt($curl, CURLOPT_POSTFIELDS, $curlPost);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_TIMEOUT, 10);
        $data = curl_exec($curl);//运行curl
        curl_close($curl);
        return $data;
    }
}